package com.example.toolproject.demo.util;

import com.alibaba.fastjson.JSONObject;
import com.example.toolproject.demo.util.redis.RedisUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * @ClassName VerificationVode
 * @Description TODO  验证码生成
 * @Author lvyongwei
 * @Date 2020-05-21 10:52
 **/
@Component
public class VerificationVode {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private RedisUtil redisUtil;

    private Logger logger= LoggerFactory.getLogger(VerificationVode.class);
    /**
     * 生成验证码方法，直接调用使用
     * @param response
     * @param request
     * @throws IOException
     * @throws IOException
     */
    public void getRegister(HttpServletResponse response, HttpServletRequest request){
        try{
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            // 生成验证码文本
            String capText = captchaProducer.createText();
            request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
            // 利用生成的字符串构建图片
            BufferedImage bi = captchaProducer.createImage(capText);
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
        }catch (Exception e){
            logger.error("验证码生成失败");
        }
    }


    /**
     * 生成验证码并存入redis中，绑定唯一的uuid,前后盾分离使用
     * @param response
     * @param request
     */
    public ResultBean getRegisterCode(HttpServletResponse response, HttpServletRequest request)  {
        String key="";
        try {
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            //生成唯一UUID
            key= UUID.randomUUID().toString();
            // 生成验证码文本
            String capText = captchaProducer.createText();
            //将验证码存入redis(redisUtil工具类，时间单位为秒)
            redisUtil.set(key,capText,60);
            // 利用生成的字符串构建图片
            BufferedImage bi = captchaProducer.createImage(capText);
            BASE64Encoder encoder=new BASE64Encoder();
            //字节数组输出流
            ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
            ByteArrayOutputStream bs =new ByteArrayOutputStream();
            ImageIO.write(bi, "png", bs);
            //将生成的图片转为base64编码
            String base64Str = Base64.getEncoder().encodeToString(bs.toByteArray());
            //前端图片前缀，跟base64编码拼接在一起，src显示
            /**
             * <img src="......">
             */
            String prefix = "data:image/jpeg;base64,";
            String img=prefix+base64Str;

            /**
             * 将生成的uuid与图片编码一起
             * 生成json对象，传给前端
             * 键值分别为：uuid,img
             */
            JSONObject json=new JSONObject();
            json.put("uuid",key);
            json.put("img",img);
            return ResultBean.success(json);
        } catch (Exception e) {
            logger.info("验证码生成失败");
            return ResultBean.error("验证码生成失败");
        }
    }
}
